from django.contrib.auth.hashers import make_password
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings

import re

from .models import Role, User
from .serializer import RoleModelSerializer, UserModelSerializer
from .tasks import send_email_task
from itsdangerous import TimedJSONWebSignatureSerializer

# 发送邮件加密使用
token_serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 1800)

"""
pip install celery
pip install redis
"""


class RoleView(APIView):
    """
    角色增加
    """

    def post(self, request):
        """
        {'name': ['普通用户']}
        """
        # 获取网页提交数据
        name = request.data.get('name')  # .data只有继承APIView才可以使用
        # 获取数据库内容，用来判断角色 是否存在
        role_obj = Role.objects.filter(name=name)
        # 判断角色是否存在
        if role_obj:
            return Response({'msg': '角色存在', 'code': 400})
        # 用反序列化来进行添加
        role_serializer = RoleModelSerializer(data=request.data)
        # 校验数据
        if role_serializer.is_valid():
            role_serializer.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            return Response({'error': role_serializer.errors})


class RegisterView(APIView):
    """
    @ author: donghaiming
    @ date: 2020-09-25
    注册：
        {'username': ['xxx'], 'password1': ['xxxxxxx'], 'password2': ['xxxxxxx'],
        'phone': ['133333333333'], 'email': ['12sss3@qq.com'], 'role': ['1]}
    """

    def post(self, request):
        # 获取网页提交数据
        print(request.data)
        username = request.data.get('username')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        phone = request.data.get('phone')
        email = request.data.get('email')
        # role_id = request.data.get('role')

        # 判断数据完整性
        # if not all([username, password1, password2, phone, email, role_id]):
        #     return Response({'msg': '数据不完整', 'code': 400})

        phone_re = re.compile(r'^1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$')
        if not re.search(phone_re, phone):
            return Response({'msg': '手机号不符合规范', 'code': 400})

        # 获取数据库中数据， 用来判断用户是否存在
        user_obj = User.objects.filter(username=username)

        # 判断用户
        if user_obj:
            return Response({'msg': '用户存在', 'code': 400})

        # 判断两次密码
        if password1 == password2:
            # 反序列化添加
            # user_data = {'username': username, 'password': make_password(password1),
            #              'phone': phone, 'email': email, 'role': role_id}

            user_data = {'username': username, 'password': make_password(password1),
                         'phone': phone, 'email': email}

            user_serializer = UserModelSerializer(data=user_data)
            # 校验
            if user_serializer.is_valid():
                user_serializer.save()
                # 发邮件
                # 异步
                user_info = {'user_id': user_serializer.data.get('id')}
                # 把用户信息进行序列化
                token = token_serializer.dumps(user_info).decode()
                send_email_task(username, token, email)

                # 发手机验证码

                return Response({'msg': '注册成功', 'code': 200})
            else:

                return Response({'error': user_serializer.errors})
        else:
            return Response({'msg': '两次密码不一致', 'code': 400})


class ActiveView(APIView):

    def get(self, request):
        print(request.query_params.get('token'))
        return Response({'msg': 'OK', 'code': 200})


# celery -A mdpro worker -l info -P eventlet